﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using SuperMap.Desktop;
using SuperMap.Desktop.UI;
using SuperMap.Data;
using SuperMap.UI;
using SuperMap.Analyst;
using SuperMap.Analyst.SpatialAnalyst;

namespace DesktopPlugin1
{
    public partial class MyControl : UIUserControl
    {
        #region 定义变量
        DensityAnalystParameter densityParam = new DensityAnalystParameter();//设置密度分析参数
        private double radioDis = 600;//设置搜索半径
        private double resoLution = 5;//设置分辨率
        string fieldName;//设置密度分析字段
        String resultDatasetName;//输出数据集的名称
        private double tolerance;//设置容限

        private Workspace currentWorkspace;//获取当前工作空间
        private MapControl currentMapControl;//获取当前图层
        private Datasource outGeoDatasource;//用于保存数据的数据源
        private Datasource inGeoDatasource;//输入点数据源
        private Datasource inLineDatasource;//输入线数据源
        private DatasetVector inGeoDataset;//输入矢量数据集
        DatasetGrid resultKernelDensityGrid;//输出栅格数据集
        private DatasetVector inLineDataset;//输入线数据集


        public ContextMenuStrip myContextMenu;
        #endregion

        public MyControl()
        {
            InitializeComponent();
        }

        #region 公有函数

        //获得当前工作空间
        public void environment(Workspace workspace, MapControl mapcontrol)
        {
            this.currentWorkspace = workspace;
            this.currentMapControl = mapcontrol;
        }

        //清空数据
        public void clearData()
        {
            this.cbf1DensityID.Text = string.Empty;
            this.cbf1px.Text = string.Empty;
            this.cbf1Round.Text = string.Empty;
            this.cbf1ResultDataset.Text = string.Empty;
            this.cbf1ResultOrigin.Text = string.Empty;
            this.cbf1SouceDataset.Text = string.Empty;
            this.cbf1SouceOrigin.Text = string.Empty;

            this.cbf2DatasetsLine.Text = string.Empty;
            this.cbf2DatasetsPoint.Text = string.Empty;
            this.cbf2DataSources.Text = string.Empty;
            this.cbf2DataSourcesResult.Text = string.Empty;
            this.cbf2DatasoucesLine.Text = string.Empty;
            this.cbf2px.Text = string.Empty;
            this.ubtRound.Text = string.Empty;
            this.utb2DatasetsResult.Text = string.Empty;
            this.utb2Tolerance.Text = string.Empty;
        }

        #endregion

        #region 核密度分析

        #region 源数据

        //获得数据源并添加到下拉列表中
        private void cbf1SouceOrigin_MouseClick(object sender, MouseEventArgs e)
        {
            cbf1SouceOrigin.Items.Clear();
            try
            {
                if (currentWorkspace != null)
                {
                    for (int i = 0; i < currentWorkspace.Datasources.Count; i++)
                        cbf1SouceOrigin.Items.Add(currentWorkspace.Datasources[i].Alias);
                }
            }
            catch
            {
                MessageBox.Show("没有数据源！");
            }
        }

        //获得数据源中的数据集
        private void cbf1SouceOrigin_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbf1SouceDataset.Items.Clear();//计数字段清空
            cbf1DensityID.Items.Clear();//密度字段清空

            inGeoDatasource = currentWorkspace.Datasources[currentWorkspace.Datasources.IndexOf(cbf1SouceOrigin.Text)];
            try
            {
                if (inGeoDatasource != null)
                {
                    for (int i = 0; i < inGeoDatasource.Datasets.Count; i++)
                    {
                        if (inGeoDatasource.Datasets[i].Type == DatasetType.Point || inGeoDatasource.Datasets[i].Type == DatasetType.Line)
                            cbf1SouceDataset.Items.Add(inGeoDatasource.Datasets[i].Name);//添加到数据集下拉列表中
                    }
                }
            }
            catch { }
        }

        //获得输出数据集的名字,获得密度字段并添加到下拉列表中
        private void cbf1SourceDataset_TextChanged(object sender, EventArgs e)
        {
            cbf1DensityID.Items.Clear();

            inGeoDataset = (DatasetVector)inGeoDatasource.Datasets[inGeoDatasource.Datasets.IndexOf(cbf1SouceDataset.Text)];
            if (inGeoDataset != null)
            {
                for (int i = 0; i < inGeoDataset.FieldCount; i++)
                {
                    cbf1DensityID.Items.Add(inGeoDataset.FieldInfos[i].Name);
                }
            }
            resultDatasetName = Convert.ToString(cbf1ResultDataset.Text);
        }

        //点击密度字段后获取密度字段
        private void cbf1DensityID_TextChanged(object sender, EventArgs e)
        {
            //cbf1DensityID.Items.Clear();
            try
            {
                if (inGeoDataset != null)
                {
                    String[] datasetNames = new String[inGeoDataset.FieldCount];
                    Int32 index = 0;
                    foreach (Dataset dataset in inGeoDataset.FieldInfos)
                    {
                        datasetNames[index++] = dataset.Name;
                    }
                    cbf1SouceDataset.Items.Add(datasetNames);
                }
                cbf1DensityID.Text = cbf1DensityID.SelectedField.ToString();
            }
            catch { }
        }

        //传入密度字段到fieldName
        private void cbf1DensityID_SelectedIndexChanged(object sender, EventArgs e)
        {
            fieldName = cbf1DensityID.Text;
        }

        //设置查找半径
        private void cbf1Round_TextChanged(object sender, EventArgs e)
        {
            radioDis = Convert.ToDouble(cbf1Round.Text);
        }

        #endregion

        #region  结果数据

        //获得输出数据源的下拉列表
        private void cbf1ResultOrigin_MouseClick(object sender, MouseEventArgs e)
        {
            cbf1ResultOrigin.Items.Clear();

            if (currentWorkspace != null)
            {
                for (int i = 0; i < currentWorkspace.Datasources.Count; i++)
                    cbf1ResultOrigin.Items.Add(currentWorkspace.Datasources[i].Alias);
            }
        }

        //获得输出数据源
        private void cbf1ResultOrigin_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cbf1ResultOrigin.Items.Clear();

            outGeoDatasource = currentWorkspace.Datasources[currentWorkspace.Datasources.IndexOf(cbf1ResultOrigin.Text)];
        }

        //获得输出数据集的名称
        private void cbf1ResultDataset_TextChanged(object sender, EventArgs e)
        {
            resultDatasetName = inGeoDatasource.Datasets.GetAvailableDatasetName(cbf1ResultDataset.Text);
        }

        //获得分辨率（像元大小）
        private void cbf1px_TextChanged(object sender, EventArgs e)
        {
            resoLution = Convert.ToDouble(cbf1px.Text);
        }

        //点击取消按钮
        private void btnCancel_Click(object sender, EventArgs e)
        {
            IDockBar dockBarManage = SuperMap.Desktop.Application.ActiveApplication.MainForm.DockBarManager[typeof(MyControl)];
            dockBarManage.Visible = false;
        }

        #endregion

        #region 核密度分析算法

        //核密度分析算法
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                densityParam.Bounds = inGeoDataset.Bounds; //分析范围
                densityParam.Resolution = resoLution;//分辨率
                densityParam.SearchRadius = radioDis;//搜索半径

                //核密度算法
                resultKernelDensityGrid = DensityAnalyst.KernelDensity(densityParam, inGeoDataset, fieldName, outGeoDatasource, resultDatasetName);

            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入点图层" + ex);
            }
        }

        #endregion

        #endregion

        #region  网络核密度分析

        #region 源数据

        //获取点数据源并添加到下拉列表中
        private void cbf2DataSources_MouseClick(object sender, MouseEventArgs e)
        {
            cbf2DataSources.Items.Clear();

            try
            {
                if (currentWorkspace != null)
                {
                    for (int i = 0; i < currentWorkspace.Datasources.Count; i++)
                        cbf2DataSources.Items.Add(currentWorkspace.Datasources[i].Alias);
                }
            }
            catch
            {
                MessageBox.Show("没有数据源！");
            }
        }

        //获得点数据源中的数据集并添加到点数据集中
        private void cbf2DataSources_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbf2DatasetsPoint.Items.Clear();//点数据集清空

            inGeoDatasource = currentWorkspace.Datasources[currentWorkspace.Datasources.IndexOf(cbf2DataSources.Text)];
            try
            {
                if (inGeoDatasource != null)
                {
                    for (int i = 0; i < inGeoDatasource.Datasets.Count; i++)
                    {
                        if (inGeoDatasource.Datasets[i].Type == DatasetType.Point)//如果是点数据，加载到点数据集中
                            cbf2DatasetsPoint.Items.Add(inGeoDatasource.Datasets[i].Name);
                    }
                }
            }
            catch { }
        }

        //获取线数据源并添加到下拉列表中
        private void cbf2DatasoucesLine_MouseClick(object sender, MouseEventArgs e)
        {
            cbf2DatasoucesLine.Items.Clear();

            try
            {
                if (currentWorkspace != null)
                {
                    for (int i = 0; i < currentWorkspace.Datasources.Count; i++)
                        cbf2DatasoucesLine.Items.Add(currentWorkspace.Datasources[i].Alias);
                }
            }
            catch
            {
                MessageBox.Show("没有数据源！");
            }
        }

        //获得数据源中的数据集并添加到线数据集中
        private void cbf2DatasoucesLine_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbf2DatasetsLine.Items.Clear();//线数据集清空

            inLineDatasource = currentWorkspace.Datasources[currentWorkspace.Datasources.IndexOf(cbf2DatasoucesLine.Text)];
            try
            {
                if (inLineDatasource != null)
                {
                    for (int i = 0; i < inLineDatasource.Datasets.Count; i++)
                    {
                        if (inLineDatasource.Datasets[i].Type == DatasetType.Line)//如果是线数据，加载到线数据集中
                            cbf2DatasetsLine.Items.Add(inLineDatasource.Datasets[i].Name);
                    }
                }
            }
            catch { }
        }

        //当选择了点数据集后,获取点数据集
        private void cbf2DatasetsPoint_SelectedIndexChanged(object sender, EventArgs e)
        {
            inGeoDataset = (DatasetVector)inGeoDatasource.Datasets[inGeoDatasource.Datasets.IndexOf(cbf2DatasetsPoint.Text)];
        }

        //当选择了线数据集后,获取线数据集
        private void cbf2DatasetsLine_SelectedIndexChanged(object sender, EventArgs e)
        {
            inLineDataset = (DatasetVector)inLineDatasource.Datasets[inLineDatasource.Datasets.IndexOf(cbf2DatasetsLine.Text)];
        }

        //设置搜索半径
        private void ubtRound_TextChanged(object sender, EventArgs e)
        {
            try
            {
                radioDis = Convert.ToDouble(ubtRound.Text);
            }
            catch (Exception)
            {
                // do nothing
            }
        }

        //设置道路容差
        private void utb2Tolerance_TextChanged(object sender, EventArgs e)
        {

            try
            {
                tolerance = Convert.ToDouble(utb2Tolerance.Text);
            }
            catch (Exception)
            {
                // do nothing
            }
        }

        #endregion

        #region 结果数据



        //获取输出数据源并添加到下拉列表中
        private void cbf2DataSourcesResult_MouseClick(object sender, MouseEventArgs e)
        {
            cbf2DataSourcesResult.Items.Clear();
            try
            {
                if (currentWorkspace != null)
                {
                    for (int i = 0; i < currentWorkspace.Datasources.Count; i++)
                        cbf2DataSourcesResult.Items.Add(currentWorkspace.Datasources[i].Alias);
                }
            }
            catch
            {
                MessageBox.Show("没有数据源！");
            }
        }

        //获得输出数据源
        private void cbf2DataSourcesResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cbf2DataSourcesResult.Items.Clear();
            outGeoDatasource = currentWorkspace.Datasources[currentWorkspace.Datasources.IndexOf(cbf2DataSourcesResult.Text)];
        }

        //设置输出数据集的名称
        private void utb2DatasetsResult_TextChanged(object sender, EventArgs e)
        {
            resultDatasetName = inGeoDatasource.Datasets.GetAvailableDatasetName(utb2DatasetsResult.Text);
        }

        //获得分辨率（像元大小）
        private void cbf2px_TextChanged(object sender, EventArgs e)
        {
            try
            {
                resoLution = Convert.ToDouble(cbf2px.Text);

            }
            catch
            { }
        }

        //取消按钮
        private void uiButton1_Click(object sender, EventArgs e)
        {
            this.btnCancel_Click(sender, e);
        }
        #endregion

        #region 网络核密度分析算法

        //网络核密度分析算法
        private void uiButton2_Click(object sender, EventArgs e)
        {
            Stopwatch time = new Stopwatch();
            time.Start();

            NetDenAnalysist netDenAnalysist = new NetDenAnalysist();//网络核密度分析算法

            //传入各种信息，输出数据集名称，道路容差，点数据集和线数据集,保存数据源,搜索半径，栅格大小
            netDenAnalysist.getInformation(resultDatasetName, tolerance, inGeoDataset, inLineDataset,
                outGeoDatasource, radioDis, resoLution);
            //将输入的点数据集填入数组中
            netDenAnalysist.getInPoints();
            //根据道路添加点集
            netDenAnalysist.FindDisPoint(inLineDataset);
            //创建网络点数据集
            netDenAnalysist.CreateNetPointDataset();
            
            Stopwatch time1 = new Stopwatch();
            time1.Start();
            //生成网络栅格化数据集并添加到图层
            currentMapControl.Map.Layers.Add(netDenAnalysist.BuildNetwork(), true);
            //添加网络栅格密度值字段
            netDenAnalysist.addFieldInfo();
            time1.Stop();
            TimeSpan ts1 = time1.Elapsed;
            SuperMap.Desktop.Application.ActiveApplication.Output.Output("创建点数据集用时" + ((ts1.TotalMilliseconds) / 1000).ToString() + "秒");

            Stopwatch time2 = new Stopwatch();
            time2.Start();
            //寻找点数据集中每个点最近的结点
            netDenAnalysist.ComputeMinDistance();
            time2.Stop();
            TimeSpan ts2 = time2.Elapsed;
            SuperMap.Desktop.Application.ActiveApplication.Output.Output("寻找最近结点用时" + ((ts2.TotalMilliseconds) / 1000).ToString()+"秒");

            //将弧段和结点一一对应
            netDenAnalysist.EdgeToNode();
            //设置交通网络分析环境
            netDenAnalysist.TransportationAnalystSetting();
            //进行服务区分析
            netDenAnalysist.ServiceAnalyst();

            Stopwatch time3 = new Stopwatch();
            time3.Start();
            //将密度值添加进数据集
            netDenAnalysist.addDensityValueToDataset();
            time3.Stop();
            TimeSpan ts3 = time3.Elapsed;
            SuperMap.Desktop.Application.ActiveApplication.Output.Output("网络核密度值计算用时" + ((ts3.TotalMilliseconds) / 1000).ToString() + "秒");

            time.Stop();
            TimeSpan ts = time.Elapsed;
            SuperMap.Desktop.Application.ActiveApplication.Output.Output("分析完毕！\n总计用时"+((ts.TotalMilliseconds)/1000).ToString()+"秒");           
        }

        #endregion

        #endregion
    }
}
